package com.su02.multi.chainrule;

import java.util.Map;

public class Power extends Function {
    private final Function f;
    private final double pow;

    private transient Function backward;

    public Power(Function f, double pow) {
        this.f = f;
        this.pow = pow;
        this.setBs(f.getBs());
    }

    @Override
    public Function doBackward(int id) {
        Function ans;
        if (isNotRelated(id)) {
            ans = new Constant(0);
        } else {
            Constant constant = new Constant(pow);
            Function powMinus1F = this.f.pow(pow - 1);
            ans = constant.mul(powMinus1F).mul(f.backward(id));
        }
        return ans;
    }

    @Override
    public double forward(Map<Integer, Double> vector) {
        assertVariablesMatch(vector);
        return Math.pow(f.forward(vector), pow);
    }
}
